<template>
  <basic-container>
    <avue-crud :option="updatedOption"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #changeFile="{row}">
        <!--        <el-button v-if="row.changeFile" type="text" @click="download(row.changeFile)">下载附件</el-button>-->
        <a class='download-link' v-if="row.changeFile" :href="row.changeFile"
           :download="`变更说明附件.${row.changeFile.substring(row.changeFile.lastIndexOf('.')+1)}`">
          <el-icon class="el-icon-document"></el-icon>
          下载</a>
      </template>
      <template slot="menuLeft" v-if="showBtn">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   plain
                   v-if="agreementInfo.medicineNo&&agreementInfo.batchId&&data.length===0"
                   @click="handleAddBtn">初次采购
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   plain
                   v-if="data.length>0"
                   @click="RetroactiveBtn">补签
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   plain
                   v-if="data.length>0"
                   @click="returnGoods">退货
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   plain
                   v-if="data.length>0"
                   @click="barter">换货
        </el-button>
      </template>
    </avue-crud>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="addDiaBox"
      :destroy-on-close="true"
      :fullscreen="false"
      append-to-body center
      width="800px"
      height="500px"
      @close="clearForm">
      <avue-form :option="option" v-model="form" @submit="rowSave">
        <template #changeFile>
          <el-upload
            :action="fileUrl"
            v-model="form.changeFile" :on-success="handleUploadSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </template>
      </avue-form>
    </el-dialog>

  </basic-container>
</template>

<script>
import {add, getDetail, getList, remove, update} from "@/api/businessTwo/agreementChange";
import option from "@/const/businessTwo/agreementChange";
import {mapGetters} from "vuex";
import {getToken} from '@/util/auth';

export default {
  name: "agreement-change",
  props: {
    agreementInfo: {
      type: Object,
      required: false,
    },
    showBtn: {
      type: Boolean,
      default: true
    },
    instId: {
      type: String,
      required: false,
    }
  },
  data() {

    return {
      uploadUrl: '',
      viewBtn1: true,
      dialogTitle: "",
      barterBox: false,
      returnGoodsBox: false,
      retroactiveBox: false,
      addDiaBox: false,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option,
      data: [],

    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.agreementChange_add, false),
        viewBtn: this.vaildData(this.permission.agreementChange_view, false),
        delBtn: this.vaildData(this.permission.agreementChange_delete, true),
        editBtn: this.vaildData(this.permission.agreementChange_edit, true)
      };
    },
    fileUrl() {
      return `/api/blade-resource/oss/endpoint/put-file?${this.website.tokenHeader}=${getToken()}`
    },
    updatedOption() {
      const newOption = Object.assign({}, this.option);
      newOption.menu = this.showBtn;
      return newOption;
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    download() {
      //console.log("================================================")
    },
    handleUploadSuccess(response) {
      // 处理上传成功后的响应数据
      //console.log("上传成功！", response);
      // 保存返回结果到某个变量
      //console.log(response.data.link)
      this.uploadUrl = response.data.name;
      this.form.changeFile = response.data.name
      //console.log(this.uploadUrl)
    },
    clearForm() {
      this.form = {};
      this.findObject(this.option.column, "amount").label = "数量";
      this.findObject(this.option.column, "changeFile").label = "附件";
    },
    handleAddBtn() {
      //debugger
      //this.addDiaLog = true;
      this.dialogTitle = "初次采购"
      this.form.changeType = "初次填报";
      this.findObject(this.option.column, "amount").label = "初次采购数量（片/袋/支）";
      this.findObject(this.option.column, "changeFile").label = "采购协议";
      this.addDiaBox = true;
      this.btnView();
    },
    RetroactiveBtn() {
      this.dialogTitle = "补签"
      this.form.changeType = "补签";
      this.findObject(this.option.column, "amount").label = "补签量（片/袋/支）";
      this.findObject(this.option.column, "changeFile").label = "补签协议";
      this.addDiaBox = true;
      this.btnView();
    },
    barter() {
      this.dialogTitle = "换货"
      this.findObject(this.option.column, "amount").label = "换货量（片/袋/支）";
      this.findObject(this.option.column, "changeFile").label = "换货协议";
      this.form.changeType = "换货";
      this.addDiaBox = true;
      this.btnView();
    },
    btnView() {
      this.viewBtn1 = true;
      this.findObject(this.option.column, "changeFile").display = true;
    },
    returnGoods() {
      // console.log("============================================================================")
      this.dialogTitle = "退货"
      this.viewBtn1 = false;
      this.form.changeType = "退货";
      this.findObject(this.option.column, "changeFile").display = false;
      this.findObject(this.option.column, "amount").label = "退货量（片/袋/支）";
      this.addDiaBox = true;
    },

    rowSave(row, done, loading) {
      //console.log(this.uploadUrl);
      row.changeFile = this.uploadUrl;
      //console.log(row.changeFile);

      // console.log(this.agreementInfo);
      row.batchId = this.agreementInfo.batchId;
      row.batchDetailId = this.agreementInfo.batchDetailId;
      row.deliveryCompanyId = this.agreementInfo.deliveryCompanyId;
      if (!row.deliveryCompanyId || row.deliveryCompanyId === "") {
        done();
        this.form = {};
        this.uploadUrl = '';
        this.$message.warning("请选择配送企业");
        return; // 阻止代码继续执行
      }

      row.medicineNo = this.agreementInfo.medicineNo;
      row.medicineName = this.agreementInfo.$medicineName;
      add(row)
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
          // 需要执行一下他的统计接口，对采购数量合计做刷新
          this.$emit("refreshPiece", row.medicineNo);
          this.form = {};
          //this.findObject(this.option.column, "amount").label = "数量";
          // this.findObject(this.option.column, "changeFile").label = "附件";
          this.uploadUrl = '';  //新增结束 清空这个文件上传路径
          this.addDiaBox = false; // 关闭弹窗
        })
        .catch(error => {
          loading();
          window.console.log(error);
        });
    },

    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          //this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      // this.option.column.changeType.search=false

      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      //this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      //this.loading = true;
      // console.log(params)
      //  console.log(this.agreementInfo.batchId, this.agreementInfo.medicineNo)
      //params.batchId = this.agreementInfo.batchId;
      if (this.agreementInfo.batchId && this.agreementInfo.medicineNo) {
        params.batchId = this.agreementInfo.batchId;
        params.medicineNo = this.agreementInfo.medicineNo;
        params.instId = this.instId;
        //console.log(this.instId)
      }
      // this.query.batchId=this.addForm.batchId;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        // console.log(data)

        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  },
  watch: {
    agreementInfo: {
      deep: true,
      handler() {
        // 在agreementInfo发生改变时执行的方法
        this.onLoad(this.page, this.query);
      }
    }
  },
};
</script>

<style scoped lang="scss">
@import "@/styles/variables.scss";

.download-link {
  color: $primary-color;
  font-weight: bold;
}
</style>
